//index.js
//获取应用实例
let app = getApp()
let formatTime = require('../../utils/util.js')

Page({
  data: {
    goodsList:[],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    errorMessage: "",
    errorCode: 0,
    hasNoCoupons: true,
    youhuijine:0, //优惠券金额
    curCoupon:null, // 当前选择使用的优惠券
    //curAddressData: {name: '林哲超', phone: '18511665318', address: '北京市朝阳区安翔北里10号院'},
    freight: 0,
    couponMoney: 0,
    discouMoney: 0,
    totalPrice: 0,
    totalPricePay: 0,
    coupons: [],
    popupHeight: 300,
    hideCouponPopup: true,
    hidePayPopup: true,
    couponID: 0,
    couponMoneyTips: '未选择优惠券',
    checkedCoupon: {},
    canNoUsedCoupons: [],
    canUsedCoupons: [],
    statusType: ["可用", "不可用"],
    currentType: 0,
    couponsNum: [0, 0],
    invalidList: [],
    hideInvalidPopup: true
  },
  onShow : function () {
    
  },

  onLoad: function () {
    let that = this
    this.getConfirm()
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
    
        that.setData({
          popupHeight: (750 / res.windowWidth) * res.windowHeight * (2 / 3)//换算成rpx
        })
        console.log('widthrpx:' + that.data.popupHeight)
      }
    })
   
  },

  statusTap: function (e) {
    var curType = e.currentTarget.dataset.index;
    this.data.currentType = curType
    this.setData({
      currentType: curType
    });


    this.setData({
      coupons: curType == 0 ? this.data.canUsedCoupons : this.data.canNoUsedCoupons
    });
    //this.onShow();
  },

  addAddress: function () {
    wx.navigateTo({
      url:"/pages/add-address/index"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url:"/pages/select-address/index?fromID=" + 1
    })
  },
  
  bindChangeCoupon: function (e) {
    const selIndex = e.detail.value[0] - 1;
    if (selIndex == -1) {
      this.setData({
        youhuijine: 0,
        curCoupon:null
      });
      return;
    }
    //console.log("selIndex:" + selIndex);
    this.setData({
      youhuijine: this.data.coupons[selIndex].money,
      curCoupon: this.data.coupons[selIndex]
    });
  },

  /**
   * 确认优惠券
   */
  confirmCoupon: function () {

    if (this.data.currentType == 0 && this.data.coupons.length > 0) {
      let checkedItem = this.data.coupons.filter(function (item, index, array) {
        return (item.checked == true)
      })
      // for (var i = 0; i < this.data.coupons.length; i++) {
      //   if (this.data.coupons[i].checked) {
      //     this.setData({
      //       couponMoney: this.data.coupons[i].value,
      //       couponID: this.data.coupons[i].id
      //     })
      //   }
      // }

      if (checkedItem.length > 0) {
        this.setData({
          couponMoney: checkedItem[0].value,
          couponID: checkedItem[0].id
        })
      } else {
        this.setData({
          couponMoney: 0,
          couponID: 0
        })
      }

      this.setData({
        hideCouponPopup: true,
        currentType: 0
      })
      this.getConfirmAgain()
    }
    
  },

  /**
   * 确认订单
   */
  getConfirm: function () {
    if (wx.showLoading) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    } else {
      wx.showToast({
        title: '加载中...',
        mask: true,
        duration: app.globalData.toastTimeout,
        icon: 'none',
      })
    }

    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/order/confirm'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
      },
      success: function (res) {
        console.log('confirm')
        console.log(res.data)

        if (res.data.code > app.globalData.successCode) {
          if (res.data.code == 12004) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].product.pic_url = app.globalData.imgUrl + res.data.data[i].product.file.savepath + res.data.data[i].product.file.savename
            } 
            
            that.setData({
              errorMessage: "抱歉，您本单中的以下商品已下架",
              errorCode: res.data.code,
              invalidList: res.data.data,
              hideInvalidPopup: false
            })
          } else if (res.data.code == 17001) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].product.pic_url = app.globalData.imgUrl + res.data.data[i].product.file.savepath + res.data.data[i].product.file.savename
            } 
            that.setData({
              errorMessage: "抱歉，您本单中的以下商品不支持配送",
              errorCode: res.data.code,
              invalidList: res.data.data,
              hideInvalidPopup: false
            })

          } else if (res.data.code == 12001) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].product.pic_url = app.globalData.imgUrl + res.data.data[i].product.file.savepath + res.data.data[i].product.file.savename
            } 
            that.setData({
              errorMessage: "抱歉，您本单中的以下商品库存不足",
              errorCode: res.data.code,
              invalidList: res.data.data,
              hideInvalidPopup: false
            })

          } else if (res.data.code == 13002) {
            wx.showModal({
              title: '提示',
              content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: "/pages/add-address/index?type=2"
                  })
                }
              }
            })
          } else {
            if (res.data.code == 14001) {
              res.data.error_message = '订单已提交'
            }
            wx.showModal({
              title: '提示',
              content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }
          

        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          if (res.data.data) {

            for (var i = 0; i < res.data.data.cart.length; i++) {
              res.data.data.cart[i].product.pic_url = app.globalData.imgUrl + res.data.data.cart[i].product.file.savepath + res.data.data.cart[i].product.file.savename
              res.data.data.cart[i].product.price = res.data.data.cart[i].product.price.toFixed(2)
            }
            res.data.data.contact.address = res.data.data.contact.province + res.data.data.contact.city + res.data.data.contact.district + res.data.data.contact.address

            that.setData({
              curAddressData: res.data.data.contact,
              goodsList: res.data.data.cart,
              freight: res.data.data.freight,
              couponMoney: res.data.data.coupon_money,
              discouMoney: res.data.data.discount_money,
              totalPricePay: res.data.data.totalprice_payable,
              totalPrice: res.data.data.total_price,
              couponID: res.data.data.coupon_id,
              couponMoneyTips: res.data.data.coupon_id == 0 ? "未选择优惠券" : "优惠" + res.data.data.coupon_money + "元"
            })
            
          } else {
            if (wx.showLoading)
              wx.hideLoading()
            else
              wx.hideToast()
            wx.showModal({
              title: '提示',
              content: '服务器异常',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }  
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      },
      complete: function (res) {
        if (wx.showLoading)
          wx.hideLoading()
        else
          wx.hideToast()
      }
    })
  },

  /**
   * 再次确认订单
   */
  getConfirmAgain: function () {
    let contactID = this.data.curAddressData.id
    console.log('contact_id:' + contactID)
    console.log('coupin_id:' + this.data.couponID)
    if (wx.showLoading) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    } else {
      wx.showToast({
        title: '加载中...',
        mask: true,
        duration: app.globalData.toastTimeout,
        icon: 'none',
      })
    }

    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/order/confirmagain'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        contact_id: contactID,
        coupon_id: that.data.couponID 
      },
      success: function (res) {
        console.log('confirmagain')
        console.log(res.data)

        if (res.data.code > app.globalData.successCode) {
          if (res.data.code == 12004) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].product.pic_url = app.globalData.imgUrl + res.data.data[i].product.file.savepath + res.data.data[i].product.file.savename
            }

            that.setData({
              errorMessage: "抱歉，您本单中的以下商品已下架",
              errorCode: res.data.code,
              invalidList: res.data.data,
              hideInvalidPopup: false
            })
          } else if (res.data.code == 17001) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].product.pic_url = app.globalData.imgUrl + res.data.data[i].product.file.savepath + res.data.data[i].product.file.savename
            }
            that.setData({
              errorMessage: "抱歉，您本单中的以下商品不支持配送",
              errorCode: res.data.code,
              invalidList: res.data.data,
              hideInvalidPopup: false
            })

          } else if (res.data.code == 12001) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].product.pic_url = app.globalData.imgUrl + res.data.data[i].product.file.savepath + res.data.data[i].product.file.savename
            }
            that.setData({
              errorMessage: "抱歉，您本单中的以下商品库存不足",
              errorCode: res.data.code,
              invalidList: res.data.data,
              hideInvalidPopup: false
            })

          } else if (res.data.code == 13002) {
            wx.showModal({
              title: '提示',
              content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: "/pages/add-address/index?type=2"
                  })
                }
              }
            })
          }  else {
            if (res.data.code == 14001) {
              res.data.error_message = '订单已提交'
            }
            wx.showModal({
              title: '提示',
              content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }

        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          if (res.data.data) {

            for (var i = 0; i < res.data.data.cart.length; i++) {
              res.data.data.cart[i].product.pic_url = app.globalData.imgUrl + res.data.data.cart[i].product.file.savepath + res.data.data.cart[i].product.file.savename
            }
            res.data.data.contact.address = res.data.data.contact.province + res.data.data.contact.city + res.data.data.contact.district + res.data.data.contact.address

            that.setData({
              curAddressData: res.data.data.contact,
              goodsList: res.data.data.cart,
              freight: res.data.data.freight,
              couponMoney: res.data.data.coupon_money,
              discouMoney: res.data.data.discount_money,
              totalPricePay: res.data.data.totalprice_payable,
              totalPrice: res.data.data.total_price,
              couponID: res.data.data.coupon_id,
              couponMoneyTips: res.data.data.coupon_id == 0 ? "未选择优惠券" : "优惠" + res.data.data.coupon_money + "元"
            })

          } else {
            if (wx.showLoading)
              wx.hideLoading()
            else
              wx.hideToast()
            wx.showModal({
              title: '提示',
              content: '服务器异常',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }
          
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false
        })
      },
      complete: function (res) {
        if (wx.showLoading)
          wx.hideLoading()
        else
          wx.hideToast()
      }
    })
  },
  /**
   * 返回购物车
   */
  backToCart: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 点击创建订单
   */
  createOrderTap: function () {
    this.createOrder()
  },

  /**
   * 创建订单
   */
  createOrder: function () {
    let token = wx.getStorageSync('token')
    if (wx.showLoading) {
      wx.showLoading({
        title: '去支付...',
        mask: true
      })
    } else {
      wx.showToast({
        title: '去支付...',
        mask: true,
        duration: app.globalData.toastTimeout,
        icon: 'none',
      })
    }
    let that = this
    let contactID = this.data.curAddressData.id
    console.log('contact_id:' + contactID)
    wx.request({
      url: app.apiUrl('/order/submission'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        contact_id: contactID,
        coupon_id: that.data.couponID
      },
      success: function (res) {
        console.log('creatOrder')
        if (res.data.code > app.globalData.successCode) {
          if (res.data.code == 14001) {
            res.data.error_message = '订单已提交'
          }
          wx.showModal({
            title: '提示',
            content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            showCancel: false
          })

        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          if (res.data.data) {
            that.toPaySelect(res.data.data.id, that.data.totalPricePay, res.data.data.started_at)//
          // that.toPaySelect(res.data.data.id, that.data.totalPricePay, new Date())// for test
          } else {
            if (wx.showLoading)
              wx.hideLoading()
            else
              wx.hideToast()
              wx.showModal({
                title: '提示',
                content: '服务器异常',
                showCancel: false
              })
          }
          
        }
        
        console.log(res.data)

      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false
        })
      },
      complete: function (res) {
        if (wx.showLoading) 
          wx.hideLoading()
        else
          wx.hideToast() 
      }
    })
  },

  /**
   * 优惠券选择弹出框
   */
  chooseCoupon: function () {
    this.getCoupons()

  },
  /**
   * 优惠券选择弹出框隐藏
   */
  closeCouponPopupTap: function () {
    this.setData({
      hideCouponPopup: true,
      currentType: 0
    })
  },

  /**
   * 确认优惠券
   */
  checkCoupon: function (e) {
    if (this.data.currentType == 0) {

      let index = e.currentTarget.dataset.index
      let couponsTemp = this.data.coupons
      let checkedIndex = -1
      let checkedItem = couponsTemp.filter(function (item, index, array) {
        return (item.checked == true)
      })
      console.log(checkedItem)
      if (checkedItem.length > 0) {
        couponsTemp[index].checked = couponsTemp[index].checked ? false : true
        for (var i = 0; i < couponsTemp.length; i++)
          if (i != index)
            couponsTemp[i].checked = false

      } else {
        couponsTemp[index].checked = true
      }

      this.setData({
        coupons: couponsTemp
      })

    } 
      
  },

  /**
   * 支付方式选择弹出框隐藏
   */
  closePayPopupTap: function () {
    this.setData({
      hidePayPopup: true
    })
  },

  toPaySelect: function (orderID, money, time) {
    wx.redirectTo({
      url: "/pages/pay-select/index?orderid=" + orderID + "&money=" + money + "&createtime=" + time + "&fromID=0"
    })
  },

  /**
   * 查看订单可用优惠券
   */
  getCoupons: function () {
    let token = wx.getStorageSync('token')
    let that = this
    if (wx.showLoading) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
    } else {
      wx.showToast({
        title: '加载中...',
        mask: true,
        duration: app.globalData.toastTimeout,
        icon: 'none',
      })
    }
    wx.request({
      url: app.apiUrl('/market/coupon/getcanusecoupon'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {

      },
      success: function (res) {
        console.log('getCoupons')
        if (res.data.code > app.globalData.successCode) {
          if (res.data.code == 14001) {
            res.data.error_message = '订单已提交'
          }
          wx.showModal({
            title: '提示',
            content: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            showCancel: false
          })

        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          console.log(res.data)
          if (JSON.stringify(res.data.data) != "{}") {

            let couponsNumTemp = that.data.couponsNum
            couponsNumTemp[0] = res.data.data.order_can_use_coupon.length
            couponsNumTemp[1] = res.data.data.order_cannot_use_coupon.length

            // if (res.data.data.order_can_use_coupon) {
            for (var i = 0; i < couponsNumTemp[0]; i++) {
              res.data.data.order_can_use_coupon[i].status = 0
              let dateEnd = formatTime.formatTime(new Date(res.data.data.order_can_use_coupon[i].end_at))
              let dateStart = formatTime.formatTime(new Date(res.data.data.order_can_use_coupon[i].start_at))
              res.data.data.order_can_use_coupon[i].date_from = formatTime.formatDatePoint(new Date(res.data.data.order_can_use_coupon[i].start_at)) + '-' + formatTime.formatDatePoint(new Date(res.data.data.order_can_use_coupon[i].end_at))
              res.data.data.order_can_use_coupon[i].checked = res.data.data.order_can_use_coupon[i].id == that.data.couponID ? true : false
              res.data.data.order_can_use_coupon[i].value = res.data.data.order_can_use_coupon[i].type == 1 ? res.data.data.order_can_use_coupon[i].value * 10 : res.data.data.order_can_use_coupon[i].value

            }

            for (var i = 0; i < couponsNumTemp[1]; i++) {
              res.data.data.order_cannot_use_coupon[i].status = 1
              let dateEnd = formatTime.formatTime(new Date(res.data.data.order_cannot_use_coupon[i].end_at))
              let dateStart = formatTime.formatTime(new Date(res.data.data.order_cannot_use_coupon[i].start_at))
              res.data.data.order_cannot_use_coupon[i].date_from = formatTime.formatDatePoint(new Date(res.data.data.order_cannot_use_coupon[i].start_at)) + '-' + formatTime.formatDatePoint(new Date(res.data.data.order_cannot_use_coupon[i].end_at))
              res.data.data.order_cannot_use_coupon[i].value = res.data.data.order_cannot_use_coupon[i].type == 1 ? res.data.data.order_cannot_use_coupon[i].value * 10 : res.data.data.order_cannot_use_coupon[i].value
            }


            that.setData({
              coupons: res.data.data.order_can_use_coupon,
              canNoUsedCoupons: res.data.data.order_cannot_use_coupon,
              canUsedCoupons: res.data.data.order_can_use_coupon,
              couponsNum: couponsNumTemp
            })

            if (res.data.data.order_can_use_coupon.length > 0 || res.data.data.order_cannot_use_coupon.length) {

              that.setData({
                hideCouponPopup: false
              })

            }
          } else {
            wx.showModal({
              title: '提示',
              content: '无优惠券信息',
              showCancel: false
            })
          } 
            
        }

      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '网络请求异常',
          showCancel: false
        })
      },
      complete: function (res) {
        if (wx.showLoading)
          wx.hideLoading()
        else
          wx.hideToast() 
      }
    })
  },
  /**
   * 选择某个优惠券
   */
  useCoupon: function (e) {
    let index = e.currentTarget.dataset.index
    let couponMoneyTips = "优惠" + this.data.coupons[index].account + "元"
    this.setData({
      couponMoney: this.data.coupons[index].account,
      couponMoneyTips: couponMoneyTips
    })
  }
})
